
import React, { useState, useEffect } from 'react'
import { Card, Button, Input, message, Checkbox } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import './index.less'

export default function Login() {
  let [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [rember, setRember] = useState(true)
  useEffect(() => {
    setUsername(localStorage.getItem('username'))
    setPassword(localStorage.getItem('password'))

  }, [])
  //只执行一次传空数组

  const navigate = useNavigate()
  // 路由跳转

  // 获取用户名
  function getUsername(e) {
    setUsername(e.target.value)
  }
  // 获取密码
  function getpassword(e) {
    setPassword(e.target.value)
  }
  //确定是否记住密码
  function isRember(e) {
    setRember(e.target.checked)
  }
  //记住密码
  function toRember() {
    if (rember) {
      localStorage.setItem('username', username)
      localStorage.setItem('password', password)
    }
    else{
      localStorage.removeItem('username')
      localStorage.removeItem('password')
    }
  }
  //登录
  async function login() {
    const { data } = await axios.post('/api/v1/login', { username, password })
    console.log(data);
    if (data.code === 200) {
      toRember()
      sessionStorage.setItem('token', data.token)
      message.success('登录成功');
      navigate('/dashboard')

    }
    else {
      message.error(data.message)
    }
  }
  return (
    <div className='login'>
      <Card className="main" >
        <h1>登录</h1>
        <Input size="large" onChange={getUsername} placeholder="请输入用户名" value={username} prefix={<UserOutlined />} />
        <Input.Password onChange={getpassword} size="large" placeholder="请输入密码" value={password} prefix={<LockOutlined />} />
        <br />
        <Checkbox onChange={isRember} checked={rember}>记住密码</Checkbox>
        <br />
        <br />
        <Button type="primary" onClick={login}>登录</Button>
      </Card>
    </div>
  )
}


